package com.leo.persistence.sqlSession;

import com.leo.persistence.config.BoundSql;
import com.leo.persistence.pojo.Configuration;
import com.leo.persistence.pojo.MappedStatement;
import com.leo.persistence.utils.GenericTokenParser;
import com.leo.persistence.utils.ParameterMapping;
import com.leo.persistence.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    private Connection connection;

    /**
     * 获取connection
     * 线程不安全(一个SqlSession持有一个Connection)，请在SqlSession调用层使用ThreadLocal解决
     *
     * @param configuration
     * @throws SQLException
     */
    private void getConnection(Configuration configuration) throws SQLException {
        connection = configuration.getDataSource().getConnection();
    }

    /**
     * 获取Statement
     *
     * @param configuration
     * @param mappedStatement
     * @param params
     * @return
     */
    private PreparedStatement getStatement(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        // 1. 获取connection
        if (null == connection) getConnection(configuration);

        // 2. 获取sql: select * from user where id = #{id} and username = #{name}
        //    转换sql: select * from user where id = ? and username = ?
        //    同时解析存储每个参数
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3. 获取sql预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4. 设置参数，占位符赋值 (反射)
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList(); //参数名列表
        for (int i = 0; i < parameterMappingList.size(); i++) {
            String field = parameterMappingList.get(i).getContent();
            /**
             * TODO 处理参数类型(暂不处理Map和List), 为null表示多参数(只支持多个基本类型的参数)，基本类型参数不做反射处理
             *
             */
            if (null == parameterClass || isBaseType(parameterClass)){
                //设置参数值
                preparedStatement.setObject(i + 1, params[i]);
            }else{
                //反射 获取参数对象的属性值
                Field declaredField = parameterClass.getDeclaredField(field);
                //设置暴力访问
                declaredField.setAccessible(true);
                // 获取参数值
                Object o = declaredField.get(params[0]);//参数是User对象
                //设置参数值
                preparedStatement.setObject(i + 1, o);
            }

        }

        return preparedStatement;

    }


    @Override
    public <E> List<E> executeQuery(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        // 获取Statement
        PreparedStatement statement = getStatement(configuration, mappedStatement, params);

        // 5. 执行sql
        ResultSet resultSet = statement.executeQuery();

        // 6. 封装返回结果集
        List<Object> list = new ArrayList<>();

        String resultType = mappedStatement.getResultType();
        Class<?> resultClass = getClassType(resultType);

        while (resultSet.next()) {
            // 获得返回值实例(必须有无参构造函数)
            Object o = resultClass.newInstance();
            // 获得表元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段值
                Object value = resultSet.getObject(columnName);

                try {
                    // 反射或内省，根据表字段名和entity的映射关系进行封装
                    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultClass);
                    Method writeMethod = propertyDescriptor.getWriteMethod(); //  获取属性器的写方法
                    writeMethod.invoke(o, value); //往对象的属性写值
                }catch (Exception e){
                    System.out.println("数据库字段必须少于等于entity的字段，否则映射出错，暂不处理");
                }
            }
            list.add(o);
        }

        return (List<E>) list;
    }

    @Override
    public int executeUpdate(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {

        // 获取Statement
        PreparedStatement statement = getStatement(configuration, mappedStatement, params);

        // 5. 执行sql并返回影响行数
        return statement.executeUpdate();
    }

    private Class<?> getClassType(String parameterType) {
        if (null != parameterType) {
            Class<?> clazz = null;
            try {
                clazz = Class.forName(parameterType);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            return clazz;
        }
        return null;
    }

    /**
     * 1. 将 #{} 使用 ? 替换
     * 2. 解析出 #{} 里的值并存储
     *
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        // 标记处理类：配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler tokenHandler = new ParameterMappingTokenHandler();

        // ${}的处理方式同理
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", tokenHandler);

        // 解析后的sql
        String parseSql = genericTokenParser.parse(sql);
        // 解析后的参数名
        List<ParameterMapping> parameterMappings = tokenHandler.getParameterMappings();

        return new BoundSql(parseSql, parameterMappings);
    }

    public boolean isBaseType(Class<?> className) {
        if (className.equals(java.lang.Integer.class) ||
                className.equals(java.lang.Byte.class) ||
                className.equals(java.lang.Long.class) ||
                className.equals(java.lang.Double.class) ||
                className.equals(java.lang.Float.class) ||
                className.equals(java.lang.Character.class) ||
                className.equals(java.lang.Short.class) ||
                className.equals(java.lang.Boolean.class)) {
            return true;
        }
        return false;
    }
}
